import React, { useState, useRef, useEffect } from 'react';
import style from './Seckill.module.css'
import { useLocation } from 'react-router-dom'
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import Store from "./../../store/index"
import * as actions from "./../../store/actions/marketing/index"
import { Input, Form, Button, DatePicker, ConfigProvider, Select, Space, Divider, Radio, Modal, Table, message } from 'antd'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import zhCN from 'antd/locale/zh_CN';
import { useNavigate } from 'react-router-dom';

dayjs.locale('zh-cn');
const { RangePicker } = DatePicker;

const { Search } = Input;

let index = 0;

const columns = [
    {
        title: '商品名称',
        dataIndex: 'name',
    },
    {
        title: '售价（元）',
        dataIndex: 'price',
    },
    {
        title: '库存',
        dataIndex: 'stock',
    },
    {
        title: '销量',
        dataIndex: 'sales'
    }
];

const dateFormat = 'YYYY/MM/DD';
const SeckillCV = () => {
    const [messageApi, contextHolder] = message.useMessage();
    const [data, setData] = useState(Store.getState().marketing.list)
    const location = useLocation()
    const [modalSH, setModalSH] = useState(false)
    const [copy, setCopy] = useState([])
    // console.log(location)
    useEffect(() => {
        setCopy([...data])
    }, []);
    const navigate = useNavigate()
    const [col, setCol] = useState([
        { title: '商品名称', dataIndex: 'name' },
        { title: '售价（元）', dataIndex: 'price' },
        { title: '库存', dataIndex: 'stock' },
        // { title: '优惠设置', dataIndex: '' },
        {
            title: '操作',
            dataIndex: '',
            render: (text) => (
                <div>
                    {contextHolder}
                    <Button type="link" onClick={() => shanChu(text)}>删除</Button>
                </div>
            ),
        },
    ])
    const [dataS, setDataS] = useState(Store.getState().marketing.inst)
    useEffect(() => {
        setDataS(Store.getState().marketing.inst)
    })
    const naRef = useRef()
    const [showTa, setShowTa] = useState(false)
    useEffect(() => {
        // setDataS(location.state.commodity)
        if (!location.state.txFb) {
            let a = location.state.commodity
            Store.dispatch(actions.addInst(a))
            setShowTa(true)
        } else {
            Store.dispatch(actions.addInst([]))
        }
    }, [])
    useEffect(() => {
        setDataS(Store.getState().marketing.inst)
        if (dataS.length > 0) {
            setShowTa(true)
        } else {
            setShowTa(false)
        }
    })

    const str = location.state.time
    const a = location.state.txFb
    const [arr, setArr] = useState(a ? [] : str.split('---'))

    const [timing, setTiming] = useState(a ? '' : arr[0])
    const [timing1, setTiming1] = useState(a ? '' : arr[1])
    const onChange1 = (value, dateString) => {
        // console.log(dateString);
        setTiming(dateString)
    };
    const onChange2 = (value, dateString) => {
        // console.log(dateString);
        setTiming1(dateString)
    };
    const [size, setSize] = useState('large');
    // 秒杀时段
    const [items, setItems] = useState(['8:00', '10:00', '12:00', '14:00']);
    const [name, setName] = useState('');
    const inputRef = useRef(null);
    const onNameChange = (event) => {
        setName(event.target.value);
    };
    const addItem = (e) => {
        e.preventDefault();
        setItems([...items, name || `New item ${index++}`]);
        setName('');
        setTimeout(() => {
            inputRef.current?.focus();
        }, 0);
    };
    const [moment, setMoment] = useState(a ? [] : location.state.moment)
    const handleChange = (value) => {
        console.log(value);
        let a = []
        a = (value)
        setMoment(a)
    };
    console.log(moment)
    //活动状态 
    let zt = null
    if (location.state.zt === '上线中') {
        zt = 1
    } else {
        zt = 2
    }
    const [check, setCheck] = useState(a ? 1 : zt);
    const choice = (e) => {
        console.log('radio checked', e.target.value);
        setCheck(e.target.value);
        console.log(check)
    };
    // console.log(check)
    // Modal框
    const showModal = () => {
        setModalSH(true);
        let arr = []
        dataS.forEach((el, index) => {
            arr.push(el.key)
        })
        console.log(arr)
        if (!location.state.txFb) {
            setSelectedRowKeys(arr)
        }
    };
    const handleCancel = () => {
        setModalSH(false);
    };
    const onSearch = (value) => {
        let a = value
        let arr = []
        copy.forEach(el => {
            if (!a || el.name.includes(a)) {
                arr.push(el)
            }
        })
        if (a === '') {
            arr = [...copy]
        }
        setData(arr)
    };

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const handleOk = () => {
        setModalSH(false);
        let arrX = []
        selectedRowKeys.forEach(el => {
            data.forEach(i => {
                if (i.key === el) {
                    arrX.push(i)
                }
            })
        })
        Store.dispatch(actions.addInst(arrX))
    };
    const shanChu = (b) => {
        console.log(b)
        Modal.confirm({
            title: '删除',
            icon: <ExclamationCircleOutlined />,
            content: '您确定要删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                messageApi.open({
                    type: 'success',
                    content: '删除成功',
                });
                Store.dispatch(actions.deleteInst(b))
                setDataS(Store.getState().marketing.inst)
            },
            onCancel() {
                messageApi.open({
                    type: 'error',
                    content: '删除失败',
                });
            }
        })
    }
    // 确定，取消
    const determine = () => {
        const a = naRef.current.input.value
        let b = '123'
        if (timing !== '' && timing1 !== '') {
            b = timing + '---' + timing1
        } else {
            b = ''
        }
        let status = ''
        if (check === 1) {
            status = '上线中'
        } else {
            status = '已下线'
        }
        setDataS(Store.getState().marketing.inst)
        let c = dataS
        let e = 0
        dataS.forEach(el => {
            console.log(el)
            e += el.stock
        })
        let f = moment
        console.log(f)
        let addObj = { name: a, time: b, quantity: e, state: '未开始', zt: status, commodity: c, moment: f }
        let editObj = { key: location.state.key, id: location.state.id, name: a, time: b, quantity: e, state: location.state.state, zt: status, commodity: c, moment: f }
        const txFb = location.state.txFb
        let abc = (a !== '') && (b !== '') && (status !== '') && (moment.length !== 0)
        if (abc && txFb) {
            Store.dispatch(actions.addArr(addObj))
            navigate(-1)
        } else if (!txFb && abc) {
            Store.dispatch(actions.editArr(editObj))
            navigate(-1)
        } else {
            messageApi.open({
                type: 'error',
                content: '数据不完整',
            });
            return
        }
    }
    const Cancel = () => {
        navigate(-1)
    }
    const tiShi = () => {
        messageApi.info('Hello, Ant Design!')
    }
    return (
        <ConfigProvider locale={zhCN}>
            <div className={style.tjBj}>
                <div>
                    <h1 className={style.title}>{location.state.title}</h1>
                </div>
                <div className={style.son1}>
                    <h4>基本信息</h4>
                    <div style={{ marginTop: '20px' }}>
                        <Form
                            labelCol={{
                                span: 3,
                            }}
                            wrapperCol={{
                                span: 14,
                            }}
                            layout="horizontal"
                        >
                            <Form.Item colon={false} label='秒杀名称' name='秒杀名称' rules={[
                                { required: true, }
                            ]} initialValue={location.state.name}>
                                <Input style={{ width: 348 }} placeholder="请输入名称" allowClear ref={naRef} />
                            </Form.Item>
                            <Form.Item colon={false} label='活动时间' name='活动时间' rules={[
                                { required: true, }
                            ]}>
                                <div>
                                    <DatePicker showTime onChange={onChange1} defaultValue={location.state.txFb ? null : dayjs(arr[0])} />
                                    <span style={{ margin: '0 10px' }}>至</span>
                                    <DatePicker showTime onChange={onChange2} defaultValue={location.state.txFb ? null : dayjs(arr[1])} />
                                </div>
                            </Form.Item>
                            <Form.Item colon={false} label='秒杀时段 ' name='秒杀时段 ' rules={[
                                { required: true, }
                            ]}>
                                <div>
                                    <Select
                                        mode="multiple"
                                        style={{
                                            width: 300,
                                        }}
                                        defaultValue={moment}
                                        onChange={handleChange}
                                        placeholder="请选择时间段"
                                        dropdownRender={(menu) => (
                                            <>
                                                {menu}
                                                <Divider
                                                    style={{
                                                        margin: '8px 0',
                                                    }}
                                                />
                                                <Space
                                                    style={{
                                                        padding: '0 8px 4px',
                                                    }}
                                                >
                                                    <Input
                                                        placeholder="请添加时间"
                                                        ref={inputRef}
                                                        value={name}
                                                        onChange={onNameChange}
                                                    />
                                                    <Button type="text" icon={<PlusOutlined />} onClick={addItem}>
                                                        添加时间
                                                    </Button>
                                                </Space>
                                            </>
                                        )}
                                        options={items.map((item) => ({
                                            label: item,
                                            value: item,
                                        }))}
                                    />
                                </div>
                            </Form.Item>
                            <Form.Item colon={false} label='活动状态  ' name='活动状态  ' rules={[
                                { required: true, }
                            ]}>
                                <div>
                                    <Radio.Group onChange={choice} defaultValue={check}>
                                        <Radio value={1}>上线</Radio>
                                        <Radio value={2}>下线</Radio>
                                    </Radio.Group>
                                </div>
                            </Form.Item>
                            <h4>商品设置</h4>
                            <Form.Item>
                                <div className={style.an1}>
                                    <Button size={size} onClick={showModal}>选择商品</Button>
                                </div>
                            </Form.Item>
                            {
                                showTa ? <Form.Item>
                                    <div className={style.an1}>
                                        <Table columns={col} dataSource={dataS} pagination={{ pageSize: 5, total: dataS.length, showTotal: total => `共${total}条`, showQuickJumper: true }} />
                                    </div>
                                </Form.Item> : null
                            }
                            <Form.Item>
                                <div className={style.an}>
                                    {contextHolder}
                                    <Button style={{ width: 89 }} type="primary" size={size} onClick={determine} >确定</Button>
                                    <Button style={{ width: 89 }} size={size} onClick={Cancel}>取消</Button>
                                </div>
                            </Form.Item>
                        </Form>
                    </div>
                </div>
                <div>
                    <Modal title="选择商品" width={739} open={modalSH} onOk={handleOk} onCancel={handleCancel} >
                        <div style={{ float: 'right', marginBottom: '10px' }}>
                            <Search
                                placeholder="请输入商品名称"
                                onSearch={onSearch}
                                style={{
                                    width: 200,
                                }}
                            />
                        </div>
                        <div>
                            <Table rowSelection={rowSelection} columns={columns} dataSource={data} pagination={{ pageSize: 5, total: data.length, showTotal: total => `共${total}条`, showQuickJumper: true }} />
                        </div>
                    </Modal>
                </div>
            </div>
        </ConfigProvider>
    );
}

export default SeckillCV;
